package com.kehutong.payfees.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import com.kehutong.common.DoveClient;
import com.kehutong.common.IpUtils;
import com.kehutong.common.util.Token;
import com.kehutong.payfees.entity.record.ChargeRecord;
import com.kehutong.payfees.util.BasicClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import javax.servlet.http.HttpServletRequest;

@WebService("/payfees/charge/record")
public class ChargeRecordServiceImpl {
    @Inject
    private DoveClient doveClient;
    @Inject
    private BasicClient basicClient;
    @Inject
    private JdbcSession jdbcSession;


    public void setDepartmentNo(ChargeRecord entity, String companyNo) throws Exception {
        JSONObject community = basicClient.getCommunityById(companyNo,
                entity.getCommunityNo());
        if(Objects.nonEmpty(community)){
            String parent_id = community.getString("parent_id");
            if(Objects.nonEmpty(parent_id)){
                entity.setDepartmentNo(parent_id);
            }
            JSONArray parent_ids = community.getJSONArray("parent_ids");
            if(Objects.nonEmpty(parent_ids)){
                List<String> departmentNos = JSONObject.parseArray(parent_ids.toJSONString(), String.class);
                entity.setDepartmentNos(departmentNos);
            }
        }
    }

    /**
     *
     * @param token
     * @param requset
     * @param cr
     * @param body
     * @param attach
     * @param payType
     *  wxpay_web 二维码支付, wxpay_wap 公众号支付, wxpay_mp 小程序支付,PAP 代扣
     * @return
     * @throws Exception
     */
    public JSONObject createUnifiedOrderByChargeRecord(Token token, HttpServletRequest requset, ChargeRecord cr, String body, String attach,String payType) throws Exception {
        JSONObject json = new JSONObject();
        json.put("subOrderNo", cr.getId());
        json.put("spbill_create_ip", IpUtils.getAddr(requset));
        json.put("total_fee", cr.getAmt().multiply(new BigDecimal(100)).setScale(0, RoundingMode.HALF_UP).toPlainString());
        json.put("openid", cr.getOpenid());
        json.put("tradeType", cr.getTradeType());
//        json.put("productId", cr.getProductId());
//        json.put("appid", token.getSuiteId());
        json.put("body", body);
        json.put("attach", attach);
        json.put("communityNo", cr.getCommunityNo());
        json.put("companyNo", token.getCompanyNo());
        json.put("notify_url", "/payfees/charge/payment/callBack");
        json.put("payType",payType);// TODO: 按实际需求取值

        // todo 等待 提供支付接口
        JSONObject result = doveClient.post("/payment/wxpay/gateway/service/unified/create", (http) -> {
            http.setBody(json.toJSONString());
        });
        if (result.getIntValue("code") != 200) {
            throw new RuntimeException("支付接口调用失败,请联系管理员");
        }

        JSONObject data = result.getJSONObject("data");
        // 记录收款的商户id
        cr.setMchId(data.getString("mchId"));
        cr.setMchName(data.getString("mchName"));
        cr.setSubMchId(data.getString("subMchId"));
        cr.setSubmchName(data.getString("subMchName"));
        cr.setPrepayId(data.getString("prepay_id"));
        cr.setCodeUrl(data.getString("codeUrl"));
        jdbcSession.insert(cr);
        return result;
    }
}
